package com.watermoniter.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Base64;
import android.util.DisplayMetrics;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import okhttp3.FormBody;

/**
 * 作者：minj on 2017/9/12 19:30
 */
public class AppConfig {


    public static int devicePixelsHeight;
    public static int devicePixelsWidth;
    ;
    public static int deviceDensity;

    public static void initParam(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        devicePixelsWidth = dm.widthPixels;
        devicePixelsHeight = dm.heightPixels;
        deviceDensity = (int)(dm.density);
    }


    /**
     * 检测当的网络（WLAN、3G/2G）状态
     *
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }


    public static String getAppInfo(Context context) {
        try {
            String pkName = context.getPackageName();
            String versionName = context.getPackageManager().getPackageInfo(pkName, 0).versionName;
            return versionName;
        } catch (Exception e) {
        }
        return "";
    }

    public static FormBody.Builder getBasicRequestBody(Context context) {
        FormBody.Builder builder = new FormBody.Builder()
//                .add("Ver ",AppConfig.getAppCodeInfo(context)+"")
//                .add("AppUserId ","1")
//                .add("BrandId","1")
//                .add("CopId","1")
                .add("Timestamp", AppConfig.getTimeStamp());
//                .add("Platform","1");
        return builder;
    }

    public static int getAppCodeInfo(Context context) {
        try {
            String pkName = context.getPackageName();
            return context.getPackageManager().getPackageInfo(pkName, 0).versionCode;
        } catch (Exception e) {
        }
        return 0;
    }

    public static String getTimeStamp() {
        return (new SimpleDateFormat("yyyyMMddHHmmss")).format(Calendar.getInstance().getTime());
    }


    /***
     * 通过图片后缀进行不同的压缩
     * @param pathName
     * @return
     */
    public static String compressImageReturnBase64(String pathName){
        if(pathName.endsWith("jpg")){
            return compressByQualityReturnBase64(pathName,200);
        }else {
            return compressBySampleSizeReturnBase64(pathName,2);
        }
    }




    /**
     * 通过降低图片的质量来压缩图片
     * @param path 图片路径
     * @param maxSize 压缩的最大大小
     * @return 压缩后的图片位图对象
     */
    private static Bitmap compressByQuality(String path, int maxSize) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inSampleSize=2;
        Bitmap bitmap= BitmapFactory.decodeFile(path,newOpts);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        boolean isCompressed = false;
        while (baos.toByteArray().length / 1024 > maxSize) {
            quality -= 20;
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            isCompressed = true;
        }
        if (isCompressed) {
            Bitmap compressedBitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);
            recycleBitmap(bitmap);
            return compressedBitmap;
        } else {
            return bitmap;
        }


    }


    /**
     * 通过降低图片的质量来压缩图片
     * @param path 图片路径
     * @param maxSize 压缩的最大大小
     * @return 压缩后的图片位图对象
     */
    private static String compressByQualityReturnBase64(String path, int maxSize) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inSampleSize=2;
        Bitmap bitmap= BitmapFactory.decodeFile(path,newOpts);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        boolean isCompressed = false;
        while (baos.toByteArray().length / 1024 > maxSize) {
            quality -= 20;
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            isCompressed = true;
        }
        if (isCompressed) {
//            Bitmap compressedBitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);
            recycleBitmap(bitmap);
//            return compressedBitmap;
        }

        return Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);


    }


    public static String compressBySampleSizeReturnBase64(String path, int inSampleSize) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inSampleSize=inSampleSize;
        Bitmap bit= BitmapFactory.decodeFile(path,newOpts);
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.PNG, 100, bos);//参数100表示不压缩
        byte[] bytes=bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }


    /***
     *
     * @param path 图片路径
     * @param inSampleSize 压缩比例
     * @return
     */
    public static Bitmap compressBySampleSize(String path, int inSampleSize) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inSampleSize=inSampleSize;
        return BitmapFactory.decodeFile(path,newOpts);
    }

    /**
     * 回收位图对象
     *
     * @param bitmap
     */
    public static void recycleBitmap(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            System.gc();
            bitmap = null;
        }
    }






}
